<?php

namespace App\Services\Common;

use App\Constant\CacheConst;
use App\Constant\Constant;
use App\Exceptions\ExceptionHelper;
use App\Exceptions\ExceptionSms;
use App\Http\Controllers\User\LoginController;
use App\Http\Request;
use App\Models\AdminStaff;
use App\Models\Company\Company;
use App\Models\Company\CompanyStaff;
use App\Models\Label;
use App\Models\User;
use App\Models\UserInvite;
use App\Models\UserNotice;
use App\Models\UserToken;
use App\Models\WechatAuth;
use App\Services\Common\User\EasemobService;
use App\Services\Common\User\UserIntegralService;
use App\Services\Common\User\UserNoticeService;
use Cache;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class UserService extends BaseService
{
    /**
     * @param UserToken $token
     */
    public static function clearUserToken($token)
    {
        try {
            Cache::delete(sprintf(CacheConst::CACHE_USER_TOKEN, $token->token));
        } catch (\Psr\SimpleCache\InvalidArgumentException $e) {
        }
    }

    /**
     * 用户登录密码加密
     * @param $password
     * @return string
     */
    public static function syncPassWord($pass_word)
    {
        return md5(sha1($pass_word) . config('common.user_secret'));
    }

    /**
     * 登录时设置用户token
     * @param int $userId
     * @return UserToken|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public static function setUserToken(int $userId)
    {
        $clientType = Request::clientType();
        $token      = UserToken::getOneByUserId($userId, $clientType);
        if ($token) {
            // 清除之前的token缓存
            self::clearUserToken($token);
            // 重置用户token
            $token->resetToken($userId);
        } else {
            $token = UserToken::addOneToken($userId, $clientType);
        }
        return $token;
    }

    /**
     * @param $openid
     * @param WechatAuth $wechatAuth
     * @return User|\Illuminate\Database\Eloquent\Builder|Model|object|null
     * @name:storeWechatAuth
     * @author: lisa
     * @datetime: 2022/2/22 8:43
     */
    public static function storeWechatAuth($openid, WechatAuth $wechatAuth)
    {
        $user = User::getOneByOpenid($openid);
        if (!$user) {
            $user = new User();
        }
        $user->avatar    = $wechatAuth->avatar;
        $user->nick_name = $wechatAuth->nick_name;
        $user->wx_openid = $wechatAuth->openid;
        $user->save();
        return $user->refresh();
    }

    public static function registerByUnionid($unionid, WechatAuth $auth)
    {
        $user = User::getOneByUnionid($unionid);
        if (!$user) {
            $user             = new User();
            $user->avatar     = $auth->avatar;
            $user->nick_name  = $auth->nick_name;
            $user->wx_openid  = $auth->openid;
            $user->wx_unionid = $auth->unionid;
            $user->save();
            $user = $user->refresh();
        }
        return $user;
    }

    /**
     * @param User $user
     * @return array
     * @name:setLogin
     * @author: lisa
     * @datetime: 2023-11-03 13:28
     */
    public static function setLogin(User $user)
    {
        $user->setLogin();
        $token = self::setLoginToken($user);

        return [
            'token'   => $token->token,
            'unionid' => $user->wx_unionid,
            'openid'  => $user->wx_openid,
        ];
    }

    /**
     * 设置登录token
     * @param User $user
     * @return UserToken|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @name:setLoginToken
     * @author: lisa
     * @datetime: 2022/2/21 17:46
     */
    public static function setLoginToken(User $user)
    {
        $userId     = $user->id;
        $clientType = Request::clientType();
        $loginToken = UserToken::getOneByUserIdAndType($userId, $clientType);
        if ($loginToken) {
            self::clearLoginToken($loginToken);
        } else {
            $loginToken = UserToken::addOneToken($userId, $clientType);
        }
        $loginToken->resetToken($userId);
        return $loginToken;
    }

    /**
     * 清除登录token
     * @param $token
     * @name:clearLoginToken
     * @author: lisa
     * @datetime: 2022/2/21 17:42
     */
    public static function clearLoginToken($token)
    {
        try {
            \Illuminate\Support\Facades\Cache::delete(sprintf(CacheConst::CACHE_USER_TOKEN, $token->token));
        } catch (\Psr\SimpleCache\InvalidArgumentException $e) {
        }
    }

    /**
     * 检查身份证号码是否真实
     * @param $idCard
     * @return bool
     */
    public static function checkIdCard($idCard)
    {
        $idCard    = strtoupper($idCard);
        $regx      = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
        $arr_split = [];
        if (!preg_match($regx, $idCard)) {
            return false;
        }
        if (15 == strlen($idCard)) { //检查15位
            $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";

            preg_match($regx, $idCard, $arr_split);
            //检查生日日期是否正确
            $dtm_birth = "19" . $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
            if (!strtotime($dtm_birth)) {
                return false;
            } else {
                return true;
            }
        } else {       //检查18位
            $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
            preg_match($regx, $idCard, $arr_split);
            $dtm_birth = $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
            if (!strtotime($dtm_birth)) {
                //检查生日日期是否正确
                return false;
            } else {
                //检验18位身份证的校验码是否正确。
                //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
                $arr_int = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                $arr_ch  = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
                $sign    = 0;
                for ($i = 0; $i < 17; $i++) {
                    $b    = (int)$idCard[$i];
                    $w    = $arr_int[$i];
                    $sign += $b * $w;
                }
                $n       = $sign % 11;
                $val_num = $arr_ch[$n];
                if ($val_num != substr($idCard, 17, 1)) {
                    return false;
                } else {
                    return true;
                }
            }
        }
    }

    /**
     * 管理平台搜索
     * @param $mobile
     * @param $nickname
     * @param $limit
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|self[]
     * @name: getAdminList
     * @Author: caoJunWei
     * @Datetime: 2022/2/16 14:56
     */
    public static function getAdminList($mobile, $nickname, $limit)
    {
        $list = User::query();
        if (!empty($mobile)) $list->where('mobile', 'like', "%{$mobile}%");
        if (!empty($nickname)) $list->where('nickname', 'like', "%{$nickname}%");
        if (!empty($type)) $list->where('type', '=', $type);
        return $list->paginate($limit);

    }

    /**
     * 注册
     * @param $mobile
     * @param null $pass_word
     * @param array $ext
     * @return User|\Illuminate\Database\Eloquent\Builder|Model|object|null
     * @author: lisa
     * @datetime: 2023-07-13 10:16
     */
    public static function register($mobile, $pass_word = null, $ext = [])
    {
        $referral_no = $ext['referral_no'] ?? null;

        if ($referral_no) {
            $referral = User::getOneByReferralNo($referral_no);
            if (!$referral) {
                ExceptionSms::returnError("介绍码无效");
            }
        }

        $user = User::getUserByMobile($mobile);
        if (!$user) {
            $user             = new User();
            $user->inviter_no = isset($referral) && $referral ? $referral->user_no : '';
            $user->special_id = 1;
        }
        $user->mobile    = $mobile;
        $nick_name       = '用户' . substr($mobile, -4);
        $user->nick_name = $nick_name;
        if ($pass_word) $user->pass_word = self::syncPassword($pass_word);
        $user->save();

        if (isset($referral)) {
            UserService::userInvite($referral, $user);
        }
        return $user;
    }

    /**
     * 存储用户邀请
     * @param User $inviter
     * @param User $invitee
     * @name:userInvite
     * @author: lisa
     * @datetime: 2023-10-23 17:01
     */
    public static function userInvite(User $inviter, User $invitee)
    {
        $first = UserInvite::whereInviteeNo($invitee->user_no)->first();
        if (!$first) {
            UserInvite::create(['inviter_no' => $inviter->user_no, 'invitee_no' => $invitee->user_no]);
        }
    }

    /**
     * 存储员工邀请
     * @param User $user
     * @param AdminStaff $staff
     * @name:staffInvite
     * @author: lisa
     * @datetime: 2023-10-23 17:01
     */
    public static function staffInvite(User $user, AdminStaff $staff)
    {
        if (!$user->staff_id) {
            $user->staff_id = $staff->id;
            $user->save();
        }
    }

    public static function getJoinCompanies($user_id)
    {
        $list = Company::whereHas('user')->whereHas('staff', function ($query) use ($user_id) {
            $query->whereUserId($user_id);
            $query->checkYes();
        })->select(['id as company_id', 'type', 'company_name'])->get();
        return $list;
    }
}
